import sqlalchemy

from app.datatype import filter_fields
from app.datatype.milvus_content import (
    MilvusContentDetailMdl, MilvusContentCreateMdl, MilvusContent, MilvusContentDeleteMdl, MilvusContentListMdl,
    MilvusContentListFindMdl, FileList,
)
from app.initializer import g
from app.utils import db_async
from app.utils.milvus_do import MilvusDo


class MilvusContentDetailBiz(MilvusContentDetailMdl):

    async def detail(self):
        # TODO: 业务逻辑
        pass

#新增milvus索引
class MilvusContentCreateBiz(MilvusContentCreateMdl):
    async def create(self):

        async with g.db_async_session() as session:
            return await db_async.create(
                session=session,
                model=MilvusContent,
                data={
                    "milvus_index": self.milvus_index,
                    "milvus_index_id": self.milvus_index_id,
                    "file_name": self.file_name,
                    "file_path": self.file_path,
                    "file_size": self.file_size
                }
            )
    async def update_upload_status(self,milvus_content_id: int):

        async with g.db_async_session() as session:
            # 更新上传状态
            return await db_async.update(
                session=session,
                model=MilvusContent,
                data={
                    "upload_status": 1,
                },
                filter_by={"id": milvus_content_id}
            )
    async def update_upload_status_fail(self,milvus_content_id: int):

        async with g.db_async_session() as session:
            # 更新上传状态
            return await db_async.update(
                session=session,
                model=MilvusContent,
                data={
                    "upload_status": 3,
                },
                filter_by={"id": milvus_content_id}
            )
#查询知识库文件是否存在
class MilvusContentExistsBiz():

    async def exists(self,milvus_index: str, file_name: str):
        async with g.db_async_session() as session:
            data = await db_async.query_total(
                session=session,
                model=MilvusContent,
                filter_by={"milvus_index": milvus_index, "file_name": file_name,"is_deleted": 0},
            )
            return data

#删除知识库文件
class MilvusContentDeleteBiz(MilvusContentDeleteMdl):
    async def delete(self):

        async with g.db_async_session() as session:

            #如果状态为上传中禁止删除
            data = await db_async.query_total(
                session=session,
                model=MilvusContent,
                filter_by={"id": self.id, "upload_status": 0,"is_deleted": 0},
            )
            if data > 0:
                return None
            # 删除milvus索引
            milvus_do = MilvusDo()
            milvus_do.delete_by_fileName(collection_name=self.milvus_index
                                         , file_name=self.file_name)


            # 删除milvus索引mysql
            data = await db_async.update(
                session=session,
                model=MilvusContent,
                data={
                    "is_deleted": 1,
                },
                filter_by={"id": self.id}
            )
        #删除 collection + /self.milvus_index + /self.file_name 路径的文件
        file_path = f"collection/{self.milvus_index}/{self.file_name}"
        try:
            import os
            if os.path.exists(file_path):
                os.remove(file_path)
            return data
        except Exception as e:
            g.logger.error(f"删除文件失败: {file_path}, 错误: {e}")
            return False


# 查询知识库列表
class MilvusContentListBiz(MilvusContentListFindMdl):
    async def lst(self):
        #查询 sessionList 通过userid order by created_at desc 并且非删除状态
        sql_base = f"SELECT id, milvus_index_id, milvus_index, file_name, file_path, file_size, upload_status, created_at FROM {MilvusContent.__tablename__} WHERE is_deleted = 0 AND milvus_index_id = :milvus_index_id"
        params = {"milvus_index_id": self.milvus_index_id}

        if self.find_name:
            sql_base += " AND file_name LIKE :find_name"
            params["find_name"] = f"%{self.find_name}%"

        sql_base += " ORDER BY created_at DESC"
        sql = sqlalchemy.text(sql_base)
        async with g.db_async_session() as session:
            result = await session.execute(sql,params)
            rows = result.fetchall()
            field_names = list(MilvusContentListMdl.__fields__.keys())
            # 如果没有数据，返回空列表
            print("!!!!!!!rows:", rows)
            if rows is None or not rows or len(rows) == 0:
                return []

            return [MilvusContentListMdl(**dict(zip(field_names, row))).dict() for row in rows]




class FileListBiz(FileList):
    async def fileNameList(self, milvus_index: str):
        async with g.db_async_session() as session:
            data = await db_async.query_all(
                session=session,
                model=MilvusContent,
                filter_by={"is_deleted": 0,"upload_status": 1, "milvus_index": milvus_index},
                fields=self.response_fields(),
            )
            return data
